package com.cskaoyan.config;

import com.cskaoyan.service.GoodsService;
import com.cskaoyan.service.OrderService;
import com.cskaoyan.service.UserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author stone
 * @date 2022/08/29 15:19
 */
@Component
public class ServiceBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 判断的需求是多种多样，也是繁琐的
        // 还有判断：返回值类型的、参数类型、参数的个数、包、类名、方法名
        if (bean instanceof GoodsService || bean instanceof OrderService) {

            Object proxy = Enhancer.create(bean.getClass(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    // 在执行增强的过程中 做什么样的增强
                    System.out.println("hello");
                    Object invoke = method.invoke(bean, objects);
                    System.out.println("world");
                    return invoke;
                }
            });
            return proxy;
        }
        if (bean instanceof UserService) {
            Object proxy = Enhancer.create(bean.getClass(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    long start = System.currentTimeMillis();
                    Object invoke = method.invoke(bean, objects);
                    long end = System.currentTimeMillis();
                    System.out.println("执行时间：" + (end - start));
                    return invoke;
                }

            });
            return proxy;
        }
        return bean;
    }
}
